package com.hugang.juc.reference;

import java.lang.ref.SoftReference;

/**
 * 软引用示例
 *
 * @author hg
 * @date 2020/8/26 15:24
 */
public class SoftReferenceDemo {

    public static void main(String[] args) {
        memoryEnough();
//        memoryNotEnough();

    }

    /**
     * 堆内存不足时，软引用会被回收
     * -Xms5m -Xmx5m
     * 结果：
     * java.lang.Object@677327b6
     * java.lang.Object@677327b6
     * java.lang.OutOfMemoryError: Java heap space
     * 	at com.hugang.juc.reference.SoftReferenceDemo.memoryNotEnough(SoftReferenceDemo.java:32)
     * 	at com.hugang.juc.reference.SoftReferenceDemo.main(SoftReferenceDemo.java:15)
     * null
     * null
     */
    public static void memoryNotEnough(){
        Object o1 = new Object();
        SoftReference<Object> softReference = new SoftReference<>(o1);

        System.out.println(o1);
        System.out.println(softReference.get());

        o1 = null;
        try {
            byte[] bytes = new byte[10 * 1024 * 1024];
        } catch (Throwable e){
            e.printStackTrace();
        } finally {
            System.out.println(o1);
            System.out.println(softReference.get());
        }

    }

    /**
     * 堆内存充足的情况，软引用不会被回收
     * 结果：
     * java.lang.Object@677327b6
     * java.lang.Object@677327b6
     * null
     * java.lang.Object@677327b6
     */
    public static void memoryEnough(){
        Object o1 = new Object();
        SoftReference<Object> softReference = new SoftReference<>(o1);

        System.out.println(o1);
        System.out.println(softReference.get());

        o1 = null;
        System.gc();

        System.out.println(o1);
        System.out.println(softReference.get());

    }
}
